package nl.ajonker.railroad.ui.drawcommand;

import java.awt.Graphics2D;
import java.awt.Point;

import nl.ajonker.railroad.ui.Orientation;

public class CornerRailCommand extends DrawCommand {
	private Point corner;
	private int startAngle;

	public CornerRailCommand() {
		super(Orientation.W_S);
	}

	public CornerRailCommand(Orientation orientaion) {
		super(orientaion);
	}

	@Override
	protected Point calculatePoints() {
		corner = calculateCorner(start);
		startAngle = calculateStartAngle();
		return calculateEndPoint(start);
	}

	@Override
	public synchronized void drawRail(Graphics2D g2d) {
		g2d.setStroke(stroke);
		g2d.setColor(railColor);

		int r = dimension;
		g2d.drawArc(corner.x, corner.y, r, r, startAngle, -90);
		// int trainLength = 90 / rail.getLength();
		// int startAngle = calculateStartAngle();
		//
		// for (int i = 0; i < rail.getLength(); i++) {
		// if (rail.hasTrain() && rail.getTrainPosition() == i)
		// g2d.setColor(trainColor);
		// else
		// g2d.setColor(railColor);
		// g2d.drawArc(corner.x, corner.y, r, r, startAngle
		// - (i * trainLength), -trainLength);
		// }
		// return calculateEndPoint(start);
	}

	private int calculateStartAngle() {
		if (orientation == Orientation.W_S)
			return 90;
		if (orientation == Orientation.N_W)
			return 0;
		if (orientation == Orientation.E_N)
			return 270;
		if (orientation == Orientation.S_E)
			return 180;
		return 0;
	}

	private Point calculateCorner(Point start) {
		if (orientation == Orientation.W_S) {
			int x = start.x - dimension / 2;
			int y = start.y;
			return new Point(x, y);
		}
		if (orientation == Orientation.N_W) {
			int x = start.x - dimension;
			int y = start.y - dimension / 2;
			return new Point(x, y);
		}
		if (orientation == Orientation.E_N) {
			int x = start.x - dimension / 2;
			int y = start.y - dimension;
			return new Point(x, y);
		}
		if (orientation == Orientation.S_E) {
			int x = start.x;
			int y = start.y - dimension / 2;
			return new Point(x, y);
		}
		return null;
	}

	private Point calculateEndPoint(Point corner) {
		if (orientation == Orientation.W_S)
			return new Point(corner.x + dimension / 2, corner.y + dimension / 2);
		if (orientation == Orientation.N_W)
			return new Point(corner.x - dimension / 2, corner.y + dimension / 2);
		if (orientation == Orientation.E_N)
			return new Point(corner.x - dimension / 2, corner.y - dimension / 2);
		if (orientation == Orientation.S_E)
			return new Point(corner.x + dimension / 2, corner.y - dimension / 2);
		return null;
	}

}
